'use strict';

const path = require('path');

/**
 * 工作空间本地配置文件名
 */
const WORKSPACE_CONFIG_NAME = '.x3projects.json';

const WORKSPACE_SERVER_CONFIG_NAME = '.x3server.json';

const WORKSPACE_PROXY_CONFIG_NAME = '.x3proxy.json';

function isObject(obj) {
  return Object.prototype.toString(obj) === '[object Object]';
}

/**
 * 一维数组转换为二维数组
 * @returns 
 */
function arrGroup(array, subGroupLength) {
  let index = 0;
  let newArray = [];
  while (index < array.length) {
    newArray.push(array.slice(index, (index += subGroupLength)));
  }
  return newArray;
}

/**
 * 转换路径，兼容 windows 和 macOS
 */
function formatPath(targetPath) {
  if (targetPath && typeof targetPath === 'string') {
    const sep = path.sep;
    if (sep === '/') {
      return targetPath;
    }
    return targetPath.replace(/\\/g, '/');
  }
  return targetPath;
}

function sleep(timeout = 1000) {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(), timeout);
  });
}

function matchStrObj(str, obj) {
  if (typeof str === 'string' && Object.keys(obj || {}).length) {
    for (const key of Object.keys(obj)) {
      const reg = new RegExp(`\\\${${key}}`, 'g');
      str = str.replace(reg, obj[key]);
    }
  }
  return str;
}

function formatCommand(command, args) {
  const win32 = process.platform === 'win32';

  const cmd = win32 ? 'cmd' : command;
  const cmdArgs = win32 ? ['/c'].concat(command, args) : args;
  const cmdAndArgs = `${cmd} ${cmdArgs.join(' ')}`;
  return {
    cmd,
    cmdArgs,
    cmdAndArgs,
  };
}

function exec(command, args, options) {
  const { cmd, cmdArgs } = formatCommand(command, args);

  if (process.env.LOG_LEVEL === 'verbose') {
    console.log('cmd: ', cmd);
    console.log('cmdArgs: ', cmdArgs);
  }
  return require('child_process').spawn(cmd, cmdArgs, options || {});
}

function execAsync(command, args, options) {
  return new Promise((resolve, reject) => {
    const p = exec(command, args, options);
    p.on('error', (e) => {
      reject(e);
    });
    p.on('exit', (c) => {
      resolve(c);
    });
  });
}

function execCommandAsync(command, options) {
  if (command) {
    const cmdArray = command.split(' ');
    const cmd = cmdArray[0];
    if (!cmd) {
      throw new Error('命令不存在!');
    }
    const args = cmdArray.slice(1);
    return execAsync(cmd, args, {
      stdio: 'inherit',
      cwd: process.cwd(),
      ...options,
    });
  }
}

function getServerSchema() {
  return require('./server-schema').CONF_SCHEMA;
}

module.exports = {
  isObject,
  arrGroup,
  formatPath,
  sleep,
  exec,
  execAsync,
  execCommandAsync,
  formatCommand,
  matchStrObj,
  getServerSchema,
  WORKSPACE_CONFIG_NAME,
  WORKSPACE_SERVER_CONFIG_NAME,
  WORKSPACE_PROXY_CONFIG_NAME,
};
